import fs from 'fs';
import path from 'path';

type ModuleFactory<M extends EmscriptenWasm.Module> = (
    opts: EmscriptenWasm.ModuleOpts,
) => M;

export function initEmscriptenModule<T extends EmscriptenWasm.Module>(moduleFactory: ModuleFactory<T>, wasmUrl: string, ): Promise<T> {
    return new Promise((resolve) => {
        const module = moduleFactory({
            noInitialRun: true,
            locateFile(url: string): string {
                if (url.endsWith('.wasm')) return wasmUrl;
                return url;
            },
            onRuntimeInitialized() {
                delete (module as any).then;
                resolve(module);
            },
        });
    });
}



//扫描文件
export function traversalFile(dir: string): string[] {
    let retArr: string[] = [];
    let arr = fs.readdirSync(dir);
    let tempPath: string;
    arr.forEach((item) => {
        tempPath = path.join(dir, item);
        if (fs.statSync(tempPath).isDirectory()) {
            retArr = retArr.concat(traversalFile(tempPath));
        } else {
            retArr.push(tempPath);
        }
    });
    return retArr;
}


/** 过滤后缀名路径 */
export function filterExtName(pathArray: string[], reserveExt: string[]) {
    return pathArray.filter(item => {
        return reserveExt.includes(path.extname(item).slice(1));
    });
}